package com.tuanzi.loan.workflow.factory;

import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.activiti.engine.identity.Group;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.GroupEntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.system.SystemUser;
import com.tuanzi.loan.business.service.system.RoleService;
import com.tuanzi.loan.business.service.system.SystemUserService;
import com.tuanzi.loan.workflow.vo.AssigneeType;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ray
 * @date 2018/01/12
 */
@Slf4j
@Component
public class CustomGroupEntityManager extends GroupEntityManager {

	@Autowired
	private SystemUserService systemUserService;

	@Resource
	private RoleService roleService;

	@Override
	public List<Group> findGroupsByUser(String account) {

		SystemUser systemUser = systemUserService.findOneByAccount(account);

		if (systemUser == null) {
			log.warn("用户不存在 ：{}", account);
			return Lists.newArrayList();
		}

		return roleService.findAllByUserId(systemUser.getId()).parallelStream().map(x -> {
			GroupEntity groupEntity = new GroupEntity();
			groupEntity.setId(AssigneeType.ROLE + "_" + x.getCode());
			groupEntity.setName(x.getName());
			groupEntity.setType("assignment");
			groupEntity.setRevision(1);
			return groupEntity;
		}).collect(Collectors.toList());

	}
}
